package com.proxy.cglib;

import java.lang.reflect.Method;
import net.sf.cglib.proxy.CallbackHelper;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.FixedValue;
import net.sf.cglib.proxy.NoOp;

//https://github.com/cglib/cglib
public class SampleClass2 {

	public void test(){
        System.out.println("hello world");
    }

	public String test2(){
		System.out.println("hello world 2");
		return "";
	}

    public static void main(String[] args) {
    	Enhancer enhancer = new Enhancer();
    	//有些时候我们可能只想对特定的方法进行拦截，对其他的方法直接放行，不做任何操作，使用Enhancer处理这种需求同样很简单,只需要一个CallbackFilter即可
        CallbackHelper callbackHelper = new CallbackHelper(SampleClass2.class, new Class[0]) {
            @Override
            protected Object getCallback(Method method) {
                if(method.getDeclaringClass() != Object.class && method.getReturnType() == String.class){
                    return new FixedValue() {
                        @Override
                        public Object loadObject() throws Exception {
                            return "Hello cglib";
                        }
                    };
                }else{
                    return NoOp.INSTANCE;
                }
            }
        };
        enhancer.setSuperclass(SampleClass2.class);
        enhancer.setCallbackFilter(callbackHelper);
        enhancer.setCallbacks(callbackHelper.getCallbacks());
        SampleClass2 proxy = (SampleClass2) enhancer.create();
        System.out.println(proxy.hashCode());
        System.out.println(proxy.test2());
    }

}
